package com.chaoxi.picturebackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxi.picturebackend.model.entity.PictureCategory;
import com.chaoxi.picturebackend.service.PictureCategoryService;
import com.chaoxi.picturebackend.mapper.PictureCategoryMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 朱杰
* @description 针对表【picture_category(图片分类)】的数据库操作Service实现
* @createDate 2025-09-30 11:57:05
*/
@Service
public class PictureCategoryServiceImpl extends ServiceImpl<PictureCategoryMapper, PictureCategory>
    implements PictureCategoryService{
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    private static final String CATEGORY_CACHE_KEY = "picture:category:list";
    
    
    /**
     * 获取所有分类列表，先查询缓存再查询数据库
     * @return 分类列表
     */
    @Override
    public List<PictureCategory> list() {
        // 先从Redis缓存中获取
        String cachedCategories = stringRedisTemplate.opsForValue().get(CATEGORY_CACHE_KEY);
        if (cachedCategories != null) {
            // 如果缓存存在，直接返回缓存数据
            return JSONUtil.toList(cachedCategories, PictureCategory.class);
        }
        // 缓存不存在，查询数据库
        List<PictureCategory> categories = super.list();
        // 将查询结果存入Redis缓存，设置较长的过期时间（1小时）
        stringRedisTemplate.opsForValue().set(CATEGORY_CACHE_KEY, 
                                            JSONUtil.toJsonStr(categories), 
                                            6, TimeUnit.HOURS);
        
        return categories;
    }
    
    /**
     * 清除分类缓存
     */
    public void clearCategoryCache() {
        stringRedisTemplate.delete(CATEGORY_CACHE_KEY);
    }
}